﻿using System;
using System.Collections.Generic;

namespace CxExtension
{
	public class CacheDictionary<K,V>
	{
		private readonly Dictionary<K, V> mCacheMap = new Dictionary<K, V>(); //

		public event Action<Dictionary<K,V>,K> OnIndex; //
		public event Func<Dictionary<K,V>,K,V> OnIndexV; //

		public Dictionary<K,V> CacheMap { get { return mCacheMap; } }

		public V Get(K key)
		{
			V value;
			var has = mCacheMap.TryGetValue(key, out value);
			if (has) return value;

			if (OnIndex != null) OnIndex(mCacheMap, key);
			if (OnIndexV != null) value = OnIndexV(mCacheMap, key);

			return value;
		}

		public void Set(K key,V value)
		{
			mCacheMap[key] = value;
		}


		public V RawGet(K key)
		{
			V value;
			mCacheMap.TryGetValue(key, out value);
			return value;
		}
	}
}